package com.vitogiovanni.tobook;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CancellationException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.vitogiovanni.tobook.entity.localeendpoint.model.Foto;
import com.vitogiovanni.tobook.entity.localeendpoint.model.Locale;
import com.vitogiovanni.tobook.entity.utenteendpoint.Utenteendpoint;
import com.vitogiovanni.tobook.utilities.LocaleHomeTaskARPreferitiListener;
import com.vitogiovanni.tobook.utilities.NetworkChecker;
import com.vitogiovanni.tobook.utilities.UserEmailFetcher;

/**
 * A placeholder fragment containing a simple view.
 */
public class LocaleHomeFragment extends Fragment implements LocaleHomeTaskARPreferitiListener<Boolean>{

	private Locale locale;
	private View rootView;
	private boolean localePreferito;
	private ImageButton buttonPreferiti;
	private PreferitoTask preferitoTask;
	private LocaleHomeTaskARPreferitiListener<Boolean> lHPR;
	
	private String tipiLocale = "";
	private String serviziLocale = "";
	/**
	 * The fragment argument representing the section number for this fragment.
	 */
	private static final String ARG_SECTION_NUMBER = "section_number";
	private static final int REQUEST_CODE = 1;
	
	/**
	 * Returns a new instance of this fragment for the given section number.
	 */
	public static LocaleHomeFragment newInstance(int sectionNumber,
			Locale locale, boolean preferito) {
		LocaleHomeFragment fragment = new LocaleHomeFragment(locale, preferito);
		Bundle args = new Bundle();
		args.putInt(ARG_SECTION_NUMBER, sectionNumber);
		fragment.setArguments(args);
		return fragment;
	}

	public LocaleHomeFragment(Locale locale, boolean preferito) {
		this.localePreferito = preferito;
		this.locale = locale;
		lHPR = this;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.fragment_locale_home, container,
				false);
		
		LinearLayout lL = (LinearLayout) rootView.findViewById(R.id.layout_foto_home_locale);
		RelativeLayout lLb = (RelativeLayout) rootView.findViewById(R.id.layout_foto_home_locale_una_foto);
		
		ImageView imageA = (ImageView) rootView.findViewById(R.id.layout_foto_home_locale_foto1);
		ImageView imageB = (ImageView) rootView.findViewById(R.id.layout_foto_home_locale_foto2);
		ImageView imageC = (ImageView) rootView.findViewById(R.id.layout_foto_home_locale_foto3);
		ImageView imageD = (ImageView) rootView.findViewById(R.id.layout_foto_home_locale_foto_una_foto_1);
		
		List<Bitmap> listFoto = new ArrayList<Bitmap>();
		List<Foto> listFotoLocale = locale.getFoto();
		
		if(listFotoLocale!=null && listFotoLocale.size()>0){
	
			if(listFotoLocale.size()==1){	
				
				byte[] img = listFotoLocale.get(0).decodeFoto();
				ByteArrayInputStream inputStream = new ByteArrayInputStream(img);
				final BitmapFactory.Options options = new BitmapFactory.Options();
			    options.inSampleSize = 2;
			    Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, options);
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				
				lL.setVisibility(LinearLayout.GONE);
				imageD.setImageBitmap(bitmap);
			}
			
			else if(listFotoLocale.size()>2){
				
				for(int i=0; i<3; i++){
					byte[] img = listFotoLocale.get(i).decodeFoto();
					ByteArrayInputStream inputStream = new ByteArrayInputStream(img);
					final BitmapFactory.Options options = new BitmapFactory.Options();
				    options.inSampleSize = 2;
				    Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, options);
					try {
						inputStream.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
					listFoto.add(bitmap);
				}
				
				lLb.setVisibility(LinearLayout.GONE);
				
				imageA.setImageBitmap(listFoto.get(0));
				imageB.setImageBitmap(listFoto.get(1));
				imageC.setImageBitmap(listFoto.get(2));	
			}	
			else{
				lL.setVisibility(LinearLayout.GONE);
				lLb.setVisibility(LinearLayout.GONE);
			}
		}
		else{
			lL.setVisibility(LinearLayout.GONE);
			lLb.setVisibility(LinearLayout.GONE);
		}
		
		return rootView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		buttonPreferiti = (ImageButton) rootView.findViewById(R.id.button_locale_preferito);
		
		if(localePreferito){
			buttonPreferiti.setImageResource(R.drawable.ic_action_favorite_pressed);
		}else{
			buttonPreferiti.setImageResource(R.drawable.ic_action_favorite);
		}
		
		ImageButton buttonCall = (ImageButton) rootView.findViewById(R.id.button_chiama_locale);
		ImageButton buttonDirections = (ImageButton) rootView.findViewById(R.id.button_indicazioni_locale);
		Button buttonPrenotazione = (Button) rootView.findViewById(R.id.button_prenotazione_locale);
		Button buttonSegnalazione = (Button) rootView.findViewById(R.id.button_segnalazione_locale);

		TextView textViewNome = (TextView) rootView.findViewById(R.id.text_nome_locale);
		TextView textViewLocation = (TextView) rootView.findViewById(R.id.text_via_locale);
		TextView textViewWebSite = (TextView) rootView.findViewById(R.id.text_sitoWeb_locale);
		TextView textViewEmail = (TextView) rootView.findViewById(R.id.text_email_locale);
		TextView textViewTipi = (TextView) rootView.findViewById(R.id.text_tipologia_locale);
		TextView textViewServizi = (TextView) rootView.findViewById(R.id.text_servizi_locale);
		TextView textViewOrari = (TextView) rootView.findViewById(R.id.text_orari_locale);

		buttonPreferiti.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!NetworkChecker.isInternetAvailable(getActivity().getApplicationContext())) {
					NetworkChecker.noConnectionToast(getActivity().getApplicationContext());
				}
				else{	
					if(preferitoTask == null)
					{
						if(localePreferito){
							buttonPreferiti.setImageResource(R.drawable.ic_action_favorite);
							localePreferito = false;
						}else{
							buttonPreferiti.setImageResource(R.drawable.ic_action_favorite_pressed);
							localePreferito = true;
						}
						preferitoTask = (PreferitoTask) new PreferitoTask(getActivity().getApplicationContext(), lHPR).execute();
					}
					else if(preferitoTask.getStatus().equals(Status.RUNNING)){
						if(localePreferito){
							buttonPreferiti.setImageResource(R.drawable.ic_action_favorite);
							localePreferito = false;
						}else{
							buttonPreferiti.setImageResource(R.drawable.ic_action_favorite_pressed);
							localePreferito = true;
						}
						preferitoTask.cancel(true);
					}
					else if(preferitoTask.getStatus().equals(Status.FINISHED)){
						if(localePreferito){
							buttonPreferiti.setImageResource(R.drawable.ic_action_favorite);
							localePreferito = false;
						}else{
							buttonPreferiti.setImageResource(R.drawable.ic_action_favorite_pressed);
							localePreferito = true;
						}
						preferitoTask = (PreferitoTask) new PreferitoTask(getActivity().getApplicationContext(), lHPR).execute();
					}
				}
			}
		});

		buttonCall.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent callIntent = new Intent(Intent.ACTION_DIAL);
				callIntent.setData(Uri.parse("tel:" + locale.getTelefono()));
				startActivity(callIntent);
			}
		});

		buttonDirections.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				
				Location location = findMyPosition();
				
				if(location!=null){
					String url = "http://maps.google.com/maps?saddr=" + location.getLatitude()
							+ "," + location.getLongitude() + "&daddr="
							+ locale.getCoordinataY() + ","
							+ locale.getCoordinataX() + "&dirflg=d";
					Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
							Uri.parse(url));
					intent.setClassName("com.google.android.apps.maps",
							"com.google.android.maps.MapsActivity");
					startActivity(intent);
				}
				else{
					Toast.makeText(getActivity().getApplicationContext(), getResources().getString(R.string.no_position), Toast.LENGTH_SHORT).show();
				}
			}
		});

		textViewNome.setText(locale.getNome());

		if(locale.getTipologia() != null){
			List<String> tipologieLocaleTemp = new ArrayList<String>();
			for (int j = 0; j < locale.getTipologia().size(); j++) {
				tipologieLocaleTemp.add(locale.getTipologia().get(j).getName());
			}
			tipiLocale = TextUtils.join(", ", tipologieLocaleTemp);
			textViewTipi.setText(tipiLocale);
		}
		else{
			textViewTipi.setVisibility(View.GONE);
		}
		
		textViewNome.setText(locale.getNome());

		if(locale.getServizi() != null){
			List<String> serviziLocaleTemp = new ArrayList<String>();
			for (int j = 0; j < locale.getServizi().size(); j++) {
				serviziLocaleTemp.add(locale.getServizi().get(j).getName());
			}
			serviziLocale = TextUtils.join(", ", serviziLocaleTemp);
			textViewServizi.setText(serviziLocale);
		}
		else{
			textViewServizi.setVisibility(View.GONE);
		}
		
		textViewLocation.setText(locale.getVia() + ", " + locale.getCitta());
		
		if(locale.getSitoWeb()!=null){
			textViewWebSite.setText(locale.getSitoWeb());
		}
		else{
			textViewWebSite.setVisibility(View.GONE);
		}
		
		if(locale.getEmail()!=null){
			textViewEmail.setText("Invia e-mail");
		}
		else{
			textViewEmail.setVisibility(View.GONE);
		}

		textViewWebSite.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri
						.parse("http://" + locale.getSitoWeb()));
				startActivity(browserIntent);
			}
		});
		
		textViewLocation.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				String label = locale.getNome();
				String uriBegin = "geo:" + locale.getCoordinataY() + "," + locale.getCoordinataX();
				String query = locale.getCoordinataY() + "," + locale.getCoordinataX() + "(" + label + ")";
				String encodedQuery = Uri.encode(query);
				String uriString = uriBegin + "?q=" + encodedQuery;
				
				startActivity(new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(uriString)));
			}
		});

		textViewEmail.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Intent.ACTION_SENDTO);
				intent.setType("message/rfc822");
				intent.setData(Uri.parse("mailto:" + locale.getEmail()));
				intent.putExtra(Intent.EXTRA_SUBJECT, "Informazioni locale: "
						+ locale.getNome());
				intent.putExtra(Intent.EXTRA_TEXT, "");
				startActivity(Intent.createChooser(intent, ""));
			}
		});
		
		if(locale.getOrariLocale() != null){
			List<String> orariLocaleTemp = new ArrayList<String>();
			for(int j = 0; j < locale.getOrariLocale().size(); j++)
			{
				orariLocaleTemp.add(locale.getOrariLocale().get(j).getOrarioApertura().toString().substring(11, 16) 
						+ " - " + locale.getOrariLocale().get(j).getOrarioChiusura().toString().substring(11, 16));
			}
			java.util.Collections.sort(orariLocaleTemp);
			String orariLocale = TextUtils.join("\n", orariLocaleTemp);
			textViewOrari.setText(orariLocale);
		}else{
			textViewOrari.setVisibility(View.GONE);
		}
				
		buttonPrenotazione.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				
				Intent intent = new Intent(getActivity(), PrenotaActivity.class);
				intent.putExtra("localeId", locale.getNome());
				intent.putExtra("localeKey", locale.getId().toString());
				
				startActivityForResult(intent, REQUEST_CODE);
			}
		});

		buttonSegnalazione.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Intent.ACTION_SENDTO);
				intent.setType("message/rfc822");
				intent.setData(Uri.parse("mailto:" + "admin@tobook.it"));
				intent.putExtra(Intent.EXTRA_SUBJECT, "Segnalazione locale: "
						+ locale.getNome());
				intent.putExtra(Intent.EXTRA_TEXT, "");
				startActivity(Intent.createChooser(intent, ""));
			}
		});
	}
	
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		  if (requestCode == 1) {

		     if(resultCode == Activity.RESULT_OK){      
				
		    	final long start = data.getExtras().getLong("data");
				final String numPosti = String.valueOf(data.getExtras().getInt("numeroPersone"));
				
				AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
		        .setTitle(R.string.prenotazioneLocale)
		        .setMessage(R.string.inserimentoCalendar)
		        .setNegativeButton(R.string.no, null)
		        .setPositiveButton(R.string.si, new DialogInterface.OnClickListener() {

		            @Override
		            public void onClick(DialogInterface dialog, int which) {

		            	Intent intent = new Intent(Intent.ACTION_EDIT);
						intent.setType("vnd.android.cursor.item/event");
						intent.putExtra("beginTime", start);
						intent.putExtra("endTime", start + 2*60*60*1000);
						intent.putExtra("title", "Prenotazione locale " + locale.getNome() + " per "
								+ numPosti + " persone" );
						intent.putExtra("EVENT_LOCATION", locale.getCitta() + " " + locale.getVia());
						startActivity(intent);
		            }
		        });
		        
				AlertDialog dialog = builder.create();
				dialog.show();
		    	 
		     }

		  }
	}
	
	public Location findMyPosition(){
		
		String provider;
		LocationManager myLocationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
		Location location = null;
		
		Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAccuracy(Criteria.POWER_LOW);
        
        provider = myLocationManager.getBestProvider(criteria, true);
        
		try {
	        // getting GPS status
	        boolean isGPSEnabled = myLocationManager.isProviderEnabled(provider);

	        // getting network status
	        boolean isNetworkEnabled = myLocationManager.isProviderEnabled(provider);

	        if (!isGPSEnabled && !isNetworkEnabled) {
	            // no network provider is enabled
	        }
	        else {
	            if (isNetworkEnabled) {
	                if (myLocationManager != null) {
	                    location = myLocationManager.getLastKnownLocation(provider);
	                }
	            }
	            // if GPS Enabled get lat/long using GPS Services
	            if (isGPSEnabled) {
	                if (location == null) {
	                    if (myLocationManager != null) {
	                        location = myLocationManager.getLastKnownLocation(provider);
	                    }
	                }
	            }
	        }

	    } catch (Exception e) {
	        e.printStackTrace();
	    }

	    return location;
	}
	
	private class PreferitoTask extends AsyncTask<Void, Void, Boolean> {

		private LocaleHomeTaskARPreferitiListener<Boolean> callback;
		
		public PreferitoTask(Context context, LocaleHomeTaskARPreferitiListener<Boolean> cb)
		{
			this.callback = cb;
		}
		
		Context context = getActivity().getApplicationContext();
		CharSequence text = UserEmailFetcher.getEmail(context);
		String emailUtente = text.toString();
		
		@Override
		protected Boolean doInBackground(Void... params) {

			Utenteendpoint.Builder builder1 = new Utenteendpoint.Builder(
					AndroidHttp.newCompatibleTransport(), new JacksonFactory(),
					null);
			builder1 = CloudEndpointUtils.updateBuilder(builder1);
			builder1.setApplicationName("to-book");
			Utenteendpoint endpointUtente = builder1.build();
			
			boolean isPreferito = localePreferito;
			
			try{
				if(isPreferito){
					endpointUtente.aggiungiPreferito(emailUtente, locale.getId().toString()).execute();
				}
				else{
					endpointUtente.rimuoviPreferito(emailUtente, locale.getId().toString()).execute();
				}
				
				if(isCancelled()){
					if(isPreferito){
						endpointUtente.rimuoviPreferito(emailUtente, locale.getId().toString()).execute();
						isPreferito = false;
					}else{
						endpointUtente.aggiungiPreferito(emailUtente, locale.getId().toString()).execute();
						isPreferito = true;
					}
				}
				
			}catch(IOException e){
				e.printStackTrace();	
			}
			return isPreferito;
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			
			callback.onTaskCompletePreferiti(result);
		}
		
		@Override
		protected void onCancelled(Boolean result) {
			
			callback.onTaskCompletePreferiti(result);
		}
	}

	@Override
	public void onTaskCompletePreferiti(Boolean result) {
		
		try {
			localePreferito = result;
			if(localePreferito){
				//buttonPreferiti.setImageResource(R.drawable.ic_action_favorite_pressed);
			}
			else{
				//buttonPreferiti.setImageResource(R.drawable.ic_action_favorite);
			}
		/*} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();*/
		} catch (CancellationException e) {
			e.printStackTrace();
		}
		
	}

}